package com.wnhoo.smartfishtank.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.wnhoo.smartfishtank.app.LMAPP;
import com.wnhoo.smartfishtank.util.MyLog;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

/**
 * 接收udp收到的数据，把它通过广播转发出去
 */
public class UdpService extends Service {

    private static final String tag = "UdpService";
    public static final String ACTION ="com.wnhoo.service.UdpService";
    public static final String ACTION_BROADCAST = "com.wnhoo.UdpService";
    public static final String ACTION_BROADCAST_MENU_STATUS = "com.wnhoo.menu.UdpService";
    private static final String TAG = "UdpService";

    @Override
    public IBinder onBind(Intent intent) {
        MyLog.i(tag, "onBind");
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(tag, "onCreate");

    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(tag, "onStartCommand");
        startThreadUPDRevice();
        return super.onStartCommand(intent, flags, startId);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(tag, "onDestroy");
        stopThreadUPDRevice();
    }

    /**
     * 监听UDP广播回复
     */
    public void startThreadUPDRevice() {
        // TODO Auto-generated method stub
        Log.d(tag, "startThreadUPDRevice");
        isStopListenerUPDRevice = false;
        threadUPDRevice = new ThreadUPDRevice();
        threadUPDRevice.start();
    }

    /**
     * 停止监听UDP广播回复
     */
    public void stopThreadUPDRevice() {
        try {

            isStopListenerUPDRevice = true;
            if (threadUPDRevice != null) {
                //threadUPDRevice.stop();
                //MyLog.d(tag, "stopThreadUPDRevice");
                threadUPDRevice.interrupt();
                threadUPDRevice = null;
            } else {
                //MyLog.e(tag, "ThreadUPDRevice is stop.");
            }
        } catch (Exception e) {
            // TODO: handle exception
            MyLog.e(tag, e.toString());
            MyLog.exception(e);
        }
    }
    private ThreadUPDRevice threadUPDRevice;
    private boolean isStopListenerUPDRevice = false;
    private static final String UDP_HOST = "225.255.255.255";//所有主机的地址
    private static final int LAN_UDP_RECEIVE_PORT = 5000;
    /**
     * 使用MulticastSocket收UDP数据
     */
    private class ThreadUPDRevice extends Thread {
        @Override
        public void run() {

            byte[] data = new byte[1024];
            MulticastSocket ms = null;
            Log.e(tag, "try UDP Listener:" + LAN_UDP_RECEIVE_PORT);
            while (!isStopListenerUPDRevice) {
                try {
                    int port = LAN_UDP_RECEIVE_PORT;
                    //"225.255.255.255";//所有主机的地址
                    InetAddress ip_receive = InetAddress.getByName(UDP_HOST);
                    ms = new MulticastSocket(port);
                    ms.joinGroup(ip_receive);
                    Log.i(tag, "UDP:监听" + port + "中...");
                    DatagramPacket packet = new DatagramPacket(data, data.length);
                    //阻塞读
                    ms.receive(packet);
                    String message = new String(packet.getData(), 0, packet.getLength(), "utf-8");
                    String socket_address = packet.getSocketAddress().toString();
                    int beginIndex = socket_address.indexOf("/") + 1;
                    int endIndex = socket_address.indexOf(":");
                    String ip_address = socket_address.substring(beginIndex, endIndex);
                    String[] udpResult = message.split("/");
                    if(udpResult[1].substring(4).equals(LMAPP.dataPlug.getId())){
                        LMAPP.dataPlug.setId(udpResult[1]);
                        Log.i(tag, "udpResult[1].substring(1, 4)" + udpResult[1].substring(1, 4));
                        LMAPP.dataPlug.setType(Integer.parseInt(udpResult[1].substring(0, 4)));
                        Log.i(tag, "LMAPP.dataPlug" + LMAPP.dataPlug.toString());
                        sendMessageToMenu();
                    }
                } catch (Exception e4) {
                    e4.getStackTrace();
                    try {
                        Thread.sleep(3000);
                    } catch (Exception er) {
                    }
                } finally {
                    if (ms != null) ms.close();
                }
            }
            super.run();
        }
    }
    public void sendMessageToUI(String message, String ip_address) {
        Intent intent = new Intent();
        intent.putExtra("message", message);
        intent.putExtra("ip_address", ip_address);
        intent.setAction(ACTION_BROADCAST);   //设置你这个广播的action，只有和这个action一样的接受者才能接受者才能接收广播
        sendBroadcast(intent);   //发送广播
    }

    public void sendMessageToMenu() {
        Intent intent = new Intent();
        intent.setAction(ACTION_BROADCAST_MENU_STATUS);   //设置你这个广播的action，只有和这个action一样的接受者才能接受者才能接收广播
        sendBroadcast(intent);   //发送广播
        stopSelf();
    }
}
